package org.anachronos.jeep.ui.trace;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.ICellEditorValidator;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;

final class TraceFilterEditingSupport extends EditingSupport {
	private final ICellEditorValidator cellEditorValidator;
	private TextCellEditor cellEditor;
	private int columnIndex;

	TraceFilterEditingSupport(final ColumnViewer viewer, ICellEditorValidator cellEditorValidator) {
		super(viewer);
		this.cellEditorValidator = cellEditorValidator;
	}

	@Override
	protected void setValue(Object element, Object value) {
		if (value != null) {
			final TraceFilter filter = (TraceFilter) element;
			filter.setColumnFilter(columnIndex, value.toString());
		}
		getViewer().refresh();
	}

	@Override
	protected Object getValue(Object element) {
		final TraceFilter filter = (TraceFilter) element;
		return filter.getColumnFilter(columnIndex);
	}

	@Override
	protected void initializeCellEditorValue(CellEditor cellEditor,
			ViewerCell cell) {
		columnIndex = cell.getColumnIndex();
		super.initializeCellEditorValue(cellEditor, cell);
	}

	@Override
	protected CellEditor getCellEditor(Object element) {
		if (cellEditor == null) {
			final Composite parent = (Composite) getViewer().getControl();
			cellEditor = new TextCellEditor(parent, SWT.SEARCH);
			cellEditor.setValidator(cellEditorValidator);
		}
		return cellEditor;
	}

	@Override
	protected boolean canEdit(final Object element) {
		return element instanceof TraceFilter;
	}
}